

#import "NSMSearchController.h"
#import "NSMSearchAssociateController.h"

@interface _NSMSearchHomeController : UIViewController <NSMSearchHomeProtocol>
@end

@implementation _NSMSearchHomeController
@synthesize didSelectSearchItem = _didSelectSearchItem;
- (void)insertLocal:(id)obj {}
@end

@interface _NSMSearchResultController : UIViewController <NSMSearchResultProtocol>
@end

@implementation _NSMSearchResultController
@synthesize didSelectResultItem = _didSelectResultItem;
- (void)searchWithObject:(id)obj {}
@end

@interface NSMSearchController () <UISearchBarDelegate>
@property (nonatomic, strong) NSMNavSearchBar *searchBar;
@property (nonatomic, strong) NSMButton *cancelBtn;
@property (nonatomic) NSMSearchStatus searchStatus;
@property (nonatomic, strong) UIViewController *currentVC;
@end

@implementation NSMSearchController

#pragma mark - lifeCycle

#pragma mark - override

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavigationItems];
    [self initChildViewControllers];
}

- (void)initNavigationItems {
    // !!系统左右有12的留白,不如预先设置好
    CGFloat spacing = 12.f;
    CGFloat height = 32.0f;
    UIView *titleView = [UIView new];
    titleView.size = CGSizeMake(kScreenWidth-spacing*2, height);

    CGRect searchFrame = CGRectMake(0, 0, titleView.width-40, height);
    self.searchBar = [[NSMNavSearchBar alloc] initWithFrame:searchFrame];
    self.searchBar.delegate = self;
    self.searchBar.backgroundImage = [UIImage imageWithColor:THEME_NAV_COLOR];
    self.searchBar.textField.backgroundColor = UIColor.groupTableViewBackgroundColor;
    self.searchBar.placeholder = @"搜索";
    [self.searchBar setImage:BundleTemplateImage(@"nsm_search_normal")
            forSearchBarIcon:UISearchBarIconSearch
                       state:UIControlStateNormal];
    [self.searchBar setPositionAdjustment:UIOffsetMake(5, 0)
                         forSearchBarIcon:UISearchBarIconSearch];
    [titleView addSubview:self.searchBar];
    
    // UIBarButtonItem或UISearchBar的cancelButton这2个傻逼的间距系统处理很渣
    NSMButton *cancelBtn = [NSMButton new];
    cancelBtn.size = CGSizeMake(40, height);
    cancelBtn.right = titleView.width;
    cancelBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    cancelBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    cancelBtn.titleLabel.font = SystemFont(14);
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(navItemActionCancel:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:cancelBtn];
    _cancelBtn = cancelBtn;
    
    self.navigationItem.titleView = titleView;
}

- (void)initChildViewControllers {
    @nsm_weak(self)
    if (!self.homeController.didSelectSearchItem) {
        self.homeController.didSelectSearchItem = ^(id obj) {
            @nsm_strong(self)
            [self _didSelectSearchObject:obj];
        };
    }
    if (!self.associateController.didSelectAssociateItem) {
        self.associateController.didSelectAssociateItem = ^(id obj) {
            @nsm_strong(self)
            [self _didSelectSearchObject:obj];
        };
    }
    if (!self.resultController.didSelectResultItem) {
        self.resultController.didSelectResultItem = ^(id obj) {
            @nsm_strong(self)
            [self _didSelectSearchResultObject:obj];
        };
    }
    
    [self addChildViewController:self.homeController];
    [self addChildViewController:self.associateController];
    [self addChildViewController:self.resultController];
    
    UIViewController *defaultVC = self.childViewControllers.firstObject;
    [self.view addSubview:defaultVC.view];
    self.currentVC = defaultVC;
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    if (_ignoreSearchBtnAction) {
        [searchBar resignFirstResponder];
        return;
    }
    [self _didSelectSearchObject:searchBar.text];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    BOOL isEmpty = (searchBar.text.length==0);
    self.searchStatus = isEmpty? NSMSearchStatusHome: NSMSearchStatusAssociate;
    
    if (!isEmpty) [self.associateController associateWithKeywords:searchBar.text];
}

#pragma mark - setter/getter
- (UIViewController<NSMSearchHomeProtocol> *)homeController {
    if (!_homeController) {
        _homeController = _NSMSearchHomeController.new;
    }
    return _homeController;
}

- (UIViewController<NSMSearchAssociateProtocol> *)associateController {
    if (!_associateController) {
        _associateController = NSMSearchAssociateController.new;
    }
    return _associateController;
}

- (UIViewController<NSMSearchResultProtocol> *)resultController {
    if (!_resultController) {
        _resultController = _NSMSearchResultController.new;
    }
    return _resultController;
}

- (void)setSearchStatus:(NSMSearchStatus)searchStatus {
    if (_searchStatus == searchStatus) return;
    
    _searchStatus = searchStatus;
    UIViewController *targetVC = self.childViewControllers[searchStatus];
    @nsm_weak(self)
    [self transitionFromViewController:self.currentVC toViewController:targetVC duration:0 options:UIViewAnimationOptionTransitionNone animations:nil completion:^(BOOL finished) {
        @nsm_strong(self)
        self.currentVC = targetVC;
    }];
}

#pragma mark - network

#pragma mark - method/public

#pragma mark - method/private
- (void)_didSelectSearchObject:(id)obj {
    [self.searchBar resignFirstResponder];

    NSString *text = @"";
    if ([obj isKindOfClass:NSString.class])
        text = SafeString(obj);
    else if ([obj isKindOfClass:NSDictionary.class])
        text = SafeString(obj[@"title"]);
    
    self.searchBar.text = text;
    self.searchStatus = NSMSearchStatusResult;
    
    // 结果搜索
    [self.resultController searchWithObject:obj];
    // 更新历史记录
    [self.homeController insertLocal:obj];;
}

- (void)_didSelectSearchResultObject:(id)obj {
    [self.searchBar resignFirstResponder];

    // 更新历史记录
    [self.homeController insertLocal:obj];
}

#pragma mark - action
- (void)navItemActionCancel:(id)sender {
    [self.searchBar resignFirstResponder];
    
    if (_isPushed)
        [self.navigationController popViewControllerAnimated:YES];
    else
        [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
